<?php
namespace app\api\controller;

use think\Controller;

/**
 * 微信支付类
 */
class WechatPay extends Controller
{
    /***
     * 生成网页支付二维码下单
     * @param array $wechat_config 微信支付配置信息(商户号,appid等等)
     * @param string $out_trade_no 外部订单号
     * @param string $total 金额
     * @param string $notify 回调地址
     * @param string $description 商品描述
     * @return array|int[]
     */
    public function wechatPayt($wechat_config = [],$out_trade_no = '',$total = '',$notify = '',$description = ''){
        // 官方提供网址
        $url = "https://api.mch.weixin.qq.com/v3/pay/transactions/native";
        $urlarr = parse_url($url); //拆解为：[scheme=>https,host=>api.mch.weixin.qq.com,path=>/v3/pay/transactions/native]
        $time = time(); //时间戳
        $noncestr = $time;
        $appid = $wechat_config['appid'];//appID
        $mchid = $wechat_config['mchid'];//商户ID
        $xlid = $wechat_config['xlid'];//秘钥序列号 可在这个网址中查询 https://myssl.com/cert_decode.html
        $data = array();

        $data['appid'] = $appid;
        $data['mchid'] = $mchid;
        $data['description'] = $description;//商品描述
        $data['out_trade_no'] = $out_trade_no;//订单编号，订单号在微信支付里是唯一的
        $data['notify_url'] = $notify;//需根据自己的情况修改回调接口，也可以为空
        $data['amount']['total'] = intval(number_format($total,0, '.', ''));//金额 单位
        $data = json_encode($data); //变为json格式

        //签名，包含了$data数据、微信指定地址、随机数和时间
        $key = $this->getSign($data,$urlarr['path'],$noncestr,$time);
        //头部信息
        $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"',$mchid,$xlid,$noncestr,$time,$key);
        $header  = array(
            'Content-Type:'.'application/json; charset=UTF-8',
            'Accept:application/json',
            'Authorization: WECHATPAY2-SHA256-RSA2048 '.$token
        );

        //向微信接口地址提交json格式的$data和header的头部信息，得到返回值
        $ret = json_decode($this->curl_post_https($url,$data,$header),true);
        //如果是个code_url网址，则说明成功了。在微信里打开该地址测试是否能付钱。
        if(isset($ret['code_url'])){
            return ['code' => 1,'code_url' => $ret['code_url']];
        }else{
            return ['code' => 0];
        }
    }

    //微信支付签名
    public function getSign($data=array(),$url,$randstr,$time){
        $str = "POST"."\n".$url."\n".$time."\n".$randstr."\n".$data."\n";
        //$str = "POST".'\n'.$url.'\n'.$time.'\n'.$randstr.'\n'.$data.'\n';
        $key = file_get_contents('/www/wwwroot/'.$_SERVER['HTTP_HOST'].'/cert/apiclient_key.pem');//在商户平台下载的证书，注意所放路径
        $str = $this->getSha256WithRSA($str,$key); //将上传内容与api证书结合加密
        return $str;
    }

    //加密
    public function getSha256WithRSA($content, $privateKey){
        $binary_signature = "";
        $algo = "SHA256";
        openssl_sign($content, $binary_signature, $privateKey, $algo);
        $sign = base64_encode($binary_signature);
        return $sign;
    }

    public function decryptCiphertext($data = [])
    {
        $this->aesKey = '535f8a7542fd280038c235686372966e';

        $ciphertext = base64_decode($data['resource']['ciphertext']);
        $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $data['resource']['associated_data'], $data['resource']['nonce'], $this->aesKey);
        $orderData = json_decode($orderData, true);
        return $orderData;
    }

    /* PHP CURL HTTPS POST */
    public function curl_post_https($url,$data,$header){ // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在，如果出错则修改为0，默认为1
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回

        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }
}